<!--
退税结算抽屉组件
-->
<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';
import { computed, ref, watch, h, reactive } from 'vue';
import { ImageUpload, FileUpload } from '#/components/upload';

import {
  Input,
  Textarea,
  Select,
  DatePicker,
  Form,
  FormItem,
  Button,
  Card,
  Row,
  Col,
  InputNumber,
} from 'ant-design-vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { getPopupContainer } from '@vben/utils';
import { pick } from 'lodash-es';
import dayjs from 'dayjs';

import { getDictOptions } from '#/utils/dict';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import {
  refundTaxSettleAdd,
  refundTaxSettleInfo,
  refundTaxSettleInfoByOrderId,
  refundTaxSettleUpdate,
  refundTaxSettleSubmit,
  refundTaxSettleApprove,
  refundTaxSettleInvalidate,
} from '#/api/trade/refundTaxSettle';
import type { RefundTaxSettleForm } from '#/api/trade/refundTaxSettle/model';
import { orderInfo } from '#/api/trade/order';
import type { OrderVO } from '#/api/trade/order/model';
import { useBeforeCloseDiff } from '#/utils/popup';
import type { OrderForm } from '#/api/trade/order/model';
import { APPROVE_STATUS } from '../constants';
import { message, Modal } from 'ant-design-vue';
import { brandList } from '#/api/trade/brand';
import { spuList } from '#/api/trade/spu';
import { skuList } from '#/api/trade/sku';
import type { DefaultOptionType } from 'ant-design-vue/es/select';
import type { SaleContractDetailVO } from '#/api/trade/saleContract/model';
import type {
  PurchaseContractDetailForm,
  PurchaseContractDetailVO,
} from '#/api/trade/purchaseContractDetail/model';
import type { PurchaseContractForm } from '#/api/trade/purchaseContract/model';
import { carCostInfo, carCostInfoByOrderId } from '#/api/trade/carCost';
import type { CarCostVO } from '#/api/trade/carCost/model';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? '编辑退税结算' : '新增退税结算';
});

//合同数据
const saleContractDetail = ref<SaleContractDetailVO>();
const purchaseContractDetail = ref<PurchaseContractDetailForm>();
const carCost = ref<CarCostVO>();
// 品牌选项
const brandOptions = ref<DefaultOptionType[]>([]);
const brandLoading = ref(false);

// SPU选项
const spuOptions = ref<DefaultOptionType[]>([]);
const spuLoading = ref(false);

// SKU选项
const skuOptions = ref<DefaultOptionType[]>([]);
const skuLoading = ref(false);

// 过滤选项
const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().includes(input.toLowerCase());
};

// 加载品牌、SPU、SKU数据
const loadProductData = async () => {
  if (formData.value?.order?.saleContract) {
    const contract = formData.value.order.saleContract.details?.[0];

    // 设置品牌ID

    // 加载品牌选项
    brandLoading.value = true;
    try {
      const { rows } = await brandList({
        pageNum: 1,
        pageSize: 200,
      });
      brandOptions.value = rows.map((item) => ({
        label: item.brandName,
        value: item.id,
      }));
    } finally {
      brandLoading.value = false;
    }
    // 加载SPU选项
    spuLoading.value = true;
    try {
      const { rows } = await spuList({
        brandId: contract?.brandId,
        pageNum: 1,
        pageSize: 200,
      });
      spuOptions.value = rows.map((item) => ({
        label: item.spuName,
        value: item.id,
      }));
    } finally {
      spuLoading.value = false;
    }
    // 加载SKU选项
    skuLoading.value = true;
    try {
      const { rows } = await skuList({
        spuId: contract?.spuId,
        pageNum: 1,
        pageSize: 200,
      });
      skuOptions.value = rows.map((item) => ({
        label: item.skuName,
        value: item.id,
      }));
    } finally {
      skuLoading.value = false;
    }
  }
};

/**
 * 定义默认值 用于reset
 */
const defaultValues: Partial<RefundTaxSettleForm> = {
  id: undefined,
  orderId: undefined,
  deptId: undefined,
  no: undefined,
  status: APPROVE_STATUS.DRAFT,
  settleDate: undefined,
  receivedDate: undefined,

  receiveTotalAmount: undefined,
  paidTotalAmount: undefined,
  totalAmount: undefined,
  costPic: undefined,
  order: {},
  receivedDetails: [],
  paidDetails: [],
  fundedDetails: [],
};

/**
 * 表单数据ref
 */
const formData = ref(defaultValues);

type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
  [key: string]: RuleObject[];
};
/**
 * 表单校验规则
 */
const formRules = ref<AntdFormRules<RefundTaxSettleForm>>({
  settleDate: [{ required: true, message: '请输入结算日期' }],
});

/**
 * useForm解构出表单方法
 */
const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

// 计算单个收入项的结汇金额
const calculateItemSettleAmount = (item: any) => {
  const receivedAmount = item.receivedAmount || 0;
  const exchangeRate = item.exchangeRate || 0;
  item.settleAmount = receivedAmount * exchangeRate;
  calculateItemTotalReceive(item);
  calculateTotalReceived();
};

// 计算单个收入项的退税金额
const calculateItemRefundTaxAmount = (item: any) => {
  // 假设退税金额为结汇金额的10%，实际应根据业务规则计算
  const settleAmount = item.settleAmount || 0;
  item.refundTaxAmount = settleAmount * 0.1;
  calculateItemTotalReceive(item);
  calculateTotalReceived();
};

// 计算单个收入项的收入合计
const calculateItemTotalReceive = (item: any) => {
  const settleAmount = item.settleAmount || 0;
  const refundTaxAmount = item.refundTaxAmount || 0;
  item.receiveTotalAmount = settleAmount + refundTaxAmount;
};

// 计算所有收入详情的总合计
const calculateTotalReceived = () => {
  const total = formData.value!.receivedDetails!.reduce(
    (sum, item) => sum + (item.receiveTotalAmount || 0),
    0,
  );
  formData.value.receiveTotalAmount = total;
};

// 计算支出合计
const calculateTotalPaid = () => {
  const total = formData.value!.paidDetails!.reduce(
    (sum, item) => sum + (item.paidAmount || 0),
    0,
  );
  formData.value.paidTotalAmount = total;
  calculateTotalAmount();
};

// 计算垫资天数
const calculateFundedDays = (item: any) => {
  if (item.fundedStartDate && item.fundedEndDate) {
    const startDate = dayjs(item.fundedStartDate);
    const endDate = dayjs(item.fundedEndDate);
    item.fundedDays = endDate.diff(startDate, 'day') + 1;
    calculateFundedInterest(item);
  }
};

// 计算垫资利息
const calculateFundedInterest = (item: any) => {
  if (item.fundedAmount && item.fundedDays && item.fundedInterestRate) {
    // 利息 = 垫资金额 * 利率 * 天数 / 365
    item.fundedInterest = parseFloat(
      (
        (item.fundedAmount * item.fundedInterestRate * item.fundedDays) /
        365
      ).toFixed(2),
    );
  }
  calculateTotalAmount();
};

// 计算费用合计
const calculateTotalAmount = () => {
  const carCostTotal = carCost.value?.totalAmount || 0;
  const fundedAmountTotal =
    formData.value.fundedDetails?.reduce(
      (sum, item) => sum + (item.fundedAmount || 0),
      0,
    ) || 0;
  const fundedInterestTotal =
    formData.value.fundedDetails?.reduce(
      (sum, item) => sum + (item.fundedInterest || 0),
      0,
    ) || 0;
  const fundedInterestCutTotal =
    formData.value.fundedDetails?.reduce(
      (sum, item) => sum + (item.fundedInterestCut || 0),
      0,
    ) || 0;
  const fundedInverseInterestTotal =
    formData.value.fundedDetails?.reduce(
      (sum, item) => sum + (item.fundedInverseInterest || 0),
      0,
    ) || 0;

  formData.value.totalAmount =
    carCostTotal +
    fundedAmountTotal +
    fundedInterestTotal -
    fundedInterestCutTotal -
    fundedInverseInterestTotal;
};

// 添加垫资项目
const addFundedItem = () => {
  formData.value.fundedDetails = formData.value.fundedDetails || [];
  formData.value.fundedDetails.push({});
};

// 删除垫资项目
const removeFundedItem = (index: number) => {
  if (formData.value.fundedDetails && formData.value.fundedDetails.length > 0) {
    formData.value.fundedDetails.splice(index, 1);
    calculateTotalAmount();
  }
};

// 添加收入项目
const addIncomeItem = () => {
  formData.value!.receivedDetails!.push({
    receivedDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
    receivedAmount: 0,
    receivedCurrency: 'USD',
    exchangeRate: 1,
    settleAmount: 0,
    settleCurrency: 'CNY',
    refundTaxAmount: 0,
    refundTaxCurrency: 'CNY',
    receiveTotalAmount: 0,
  });
};

// 删除收入项目
const removeIncomeItem = (index: number) => {
  if (formData.value!.receivedDetails!.length > 1) {
    formData.value!.receivedDetails!.splice(index, 1);
    calculateTotalReceived();
  }
};

// 添加支出项目
const addExpenseItem = () => {
  formData.value!.paidDetails!.push({
    paidItem: 'purchase_car',
    paidAmount: 0,
    paidDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
  });
};

// 删除支出项目
const removeExpenseItem = (index: number) => {
  if (formData.value!.paidDetails!.length > 1) {
    formData.value!.paidDetails!.splice(index, 1);
    calculateTotalPaid();
  }
};

// 监听相关字段变化，自动计算

watch(() => formData.value!.receivedDetails, calculateTotalReceived, {
  deep: true,
});
watch(() => formData.value!.paidDetails, calculateTotalPaid, { deep: true });
watch(() => formData.value.fundedDetails, calculateTotalAmount, { deep: true });

function customFormValueGetter() {
  return JSON.stringify(formData.value);
}

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: customFormValueGetter,
    currentGetter: customFormValueGetter,
  },
);

const [BasicDrawer, drawerApi] = useVbenDrawer({
  class: 'w-[1200px]',
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    const { id, orderId } = drawerApi.getData() as {
      id?: number | string;
      orderId?: number | string;
    };
    isUpdate.value = !!id;

    // 如果有orderId，加载订单信息
    if (orderId) {
      try {
        const record = await refundTaxSettleInfoByOrderId(orderId);
        // 只赋值存在的字段
        const filterRecord = pick(record, Object.keys(defaultValues));
        if (record.id) {
          isUpdate.value = true;
        }
        formData.value = { ...formData.value, ...filterRecord };
        // 初始合同详情、采购详情
        saleContractDetail.value =
          formData.value.order?.saleContract?.details?.[0];
        purchaseContractDetail.value =
          formData.value.order?.purchaseContract?.details?.[0];

        // 加载品牌、SPU、SKU数据
        await loadProductData();
        // 初始化收入详情
        if (!formData.value!.receivedDetails?.length) {
          formData.value!.receivedDetails! = [
            {
              receivedAmount: 0,
              receiveTotalAmount: 0,
            },
          ];
          calculateTotalReceived();
        }
        // 初始化支出项目
        if (!formData.value!.paidDetails?.length) {
          formData.value!.paidDetails! = [
            {
              paidItem: 'purchase_car',
              paidDate:
                formData.value?.order?.purchaseContract?.contractDate ||
                dayjs().format('YYYY-MM-DD'),
              paidAmount:
                formData.value?.order?.purchaseContract?.totalAmount || 0,
            },
          ];
          calculateTotalPaid();
        }
        if (!formData.value!.fundedDetails?.length) {
          //初始化垫资项目
          formData.value!.fundedDetails! = [{}];
          calculateTotalPaid();
        }
      } catch (error) {
        console.error('加载订单信息失败:', error);
      }
    } else if (isUpdate.value && id) {
      const record = await refundTaxSettleInfo(id);

      // 只赋值存在的字段
      const filterRecord = pick(record, Object.keys(defaultValues));
      formData.value = { ...formData.value, ...filterRecord };
      // 加载品牌、SPU、SKU数据
      await loadProductData();
    }

    //加载车辆费用单
    carCost.value = await carCostInfoByOrderId(
      orderId ? orderId : formData.value.orderId!,
    );

    // 初始化费用合计计算
    calculateTotalAmount();

    await markInitialized();
    drawerApi.drawerLoading(false);
  },
});

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    await validate();
    // 可能会做数据处理 使用cloneDeep深拷贝
    const data = cloneDeep(formData.value);
    if (!data.status) {
      data.status = APPROVE_STATUS.DRAFT;
    }
    console.log('isUpdate', isUpdate.value);
    await (isUpdate.value
      ? refundTaxSettleUpdate(data)
      : refundTaxSettleAdd(data));
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

// 提交
async function handleSubmit() {
  try {
    drawerApi.lock(true);
    await validate();

    const data = cloneDeep(formData.value);
    await refundTaxSettleUpdate(data);
    await refundTaxSettleSubmit([data.id!]);
    message.success('重新提交成功');
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error('重新提交失败', error);
  } finally {
    drawerApi.lock(false);
  }
}

// 审核通过
async function handleApprove() {
  Modal.confirm({
    title: '确认审核通过？',
    content: '审核通过后将无法修改，请确认操作',
    onOk: async () => {
      try {
        await refundTaxSettleApprove(formData.value.id!, true, undefined);
        message.success('审核通过成功');
        emit('reload');
        drawerApi.close();
      } catch (error) {
        console.error('审核通过失败', error);
      }
    },
  });
}

// 驳回
async function handleReject() {
  Modal.confirm({
    title: '请输入驳回原因',
    content: h(Input.TextArea, {
      placeholder: '请输入驳回原因',
      rows: 4,
      onInput: (e: Event) => {
        rejectReason.value = (e.target as HTMLTextAreaElement).value;
      },
    }),
    onOk: async () => {
      if (!rejectReason.value.trim()) {
        message.warning('请输入驳回原因');
        return Promise.reject();
      }
      try {
        await refundTaxSettleApprove(
          formData.value.id!,
          false,
          rejectReason.value,
        );
        message.success('驳回成功');
        emit('reload');
        drawerApi.close();
      } catch (error) {
        console.error('驳回失败', error);
      }
    },
  });
}

// 作废
async function handleCancel() {
  Modal.confirm({
    title: '确认作废？',
    content: '作废后将无法恢复，请确认操作',
    onOk: async () => {
      try {
        await refundTaxSettleInvalidate(formData.value.id!);
        message.success('作废成功');
        emit('reload');
        drawerApi.close();
      } catch (error) {
        console.error('作废失败', error);
      }
    },
  });
}

const rejectReason = ref('');

// 驳回原因是否可见
const showRejectReason = computed(() => {
  return (
    formData.value.rejectReason && formData.value.rejectReason.trim() !== ''
  );
});

// 表单是否禁用 - 只有待提交、已驳回状态下才可以输入
const isFormDisabled = computed(() => {
  return (
    formData.value.status !== null &&
    formData.value.status !== APPROVE_STATUS.DRAFT &&
    formData.value.status !== APPROVE_STATUS.REJECTED
  );
});

async function handleClosed() {
  formData.value = cloneDeep(defaultValues);

  // 重置品牌、SPU、SKU相关数据
  brandOptions.value = [];
  spuOptions.value = [];
  skuOptions.value = [];
  saleContractDetail.value = {};
  purchaseContractDetail.value = {};
  resetFields();
  resetInitialized();
}
</script>

<template>
  <BasicDrawer :title="title">
    <template #footer>
      <div class="flex justify-end space-x-2">
        <!-- 提交审核 -->
        <Button
          v-if="
            formData.status === APPROVE_STATUS.DRAFT ||
            formData.status === APPROVE_STATUS.REJECTED
          "
          type="primary"
          @click="handleSubmit"
        >
          提交审核
        </Button>

        <!-- 通过 -->
        <Button
          v-if="formData.status === APPROVE_STATUS.WAITING"
          type="primary"
          @click="handleApprove"
        >
          通过
        </Button>

        <!-- 驳回 -->
        <Button
          v-if="formData.status === APPROVE_STATUS.WAITING"
          danger
          @click="handleReject"
        >
          驳回
        </Button>

        <!-- 作废 -->
        <Button
          v-if="
            formData.status === APPROVE_STATUS.DRAFT ||
            formData.status === APPROVE_STATUS.WAITING
          "
          danger
          @click="handleCancel"
        >
          作废
        </Button>

        <!-- 仅保存 -->
        <Button
          v-if="
            !formData.status ||
            formData.status === APPROVE_STATUS.DRAFT ||
            formData.status === APPROVE_STATUS.REJECTED
          "
          type="primary"
          @click="handleConfirm"
        >
          仅保存
        </Button>

        <!-- 返回 -->
        <Button @click="drawerApi.close()"> 返回 </Button>
      </div>
    </template>

    <Form :model="formData" :rules="formRules" :validate-trigger="[]">
      <div class="p-4">
        <!-- 客户信息 -->
        <Card title="客户信息" class="mb-4">
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="客户名称">
                <span>{{
                  formData.order?.saleContract?.customer?.name || '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="订单编号">
                <span>{{ formData.order?.orderNo || '-' }}</span>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="开户行">
                <span>{{
                  formData.order?.saleContract?.customer?.bankName || '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="收款账号">
                <span>{{
                  formData.order?.saleContract?.customer?.bankAccountNo || '-'
                }}</span>
              </FormItem>
            </Col>
          </Row>
        </Card>

        <!-- 商品及合同信息 -->
        <Card title="商品及合同信息" class="mb-4">
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="品牌">
                <span>{{
                  brandOptions.find(
                    (item) => item.value === saleContractDetail?.brandId,
                  )?.label || '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="SPU">
                <span>{{
                  spuOptions.find(
                    (item) => item.value === saleContractDetail?.spuId,
                  )?.label || '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="SKU">
                <span>{{
                  skuOptions.find(
                    (item) => item.value === saleContractDetail?.skuId,
                  )?.label || '-'
                }}</span>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="16">
              <FormItem label="车架号">
                <span>{{ formData?.order?.frameNo || '-' }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem
                label="结算日期"
                name="settleDate"
                :rules="[{ required: true, message: '请输入结算日期' }]"
              >
                <DatePicker
                  v-model:value="formData.settleDate"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  class="w-full"
                  :disabled="isFormDisabled"
                />
              </FormItem>
            </Col>
          </Row>

          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="销售合同号">
                <span>{{
                  formData.order?.saleContract?.contractNo || '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="销售金额">
                <span>{{
                  saleContractDetail?.amount
                    ? Number(saleContractDetail.amount).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="币种">
                <span>{{
                  getDictOptions('currency').find(
                    (item) =>
                      item.value === formData.order?.saleContract?.currency,
                  )?.label || '-'
                }}</span>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="采购合同号">
                <span>{{
                  formData.order?.purchaseContract?.contractNo || '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="采购金额">
                <span>{{
                  purchaseContractDetail?.purchaseAmount
                    ? Number(
                        purchaseContractDetail.purchaseAmount,
                      ).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="币种">
                <span>{{
                  getDictOptions('currency').find(
                    (item) =>
                      item.value === formData.order?.purchaseContract?.currency,
                  )?.label || '-'
                }}</span>
              </FormItem>
            </Col>
          </Row>
        </Card>

        <!-- 收入详情 -->
        <Card title="收入详情" class="mb-4">
          <div
            v-for="(item, index) in formData.receivedDetails"
            :key="item.id || index"
            class="income-item mb-3"
          >
            <div class="mb-3 flex items-center justify-between">
              <span class="font-medium">收入项目 {{ index + 1 }}</span>
              <Button
                type="text"
                danger
                size="small"
                :disabled="isFormDisabled"
                @click="removeIncomeItem(index)"
              >
                <DeleteOutlined /> 删除
              </Button>
            </div>
            <Row :gutter="16">
              <Col :span="8">
                <FormItem
                  label="到账日期"
                  :name="['receivedDetails', index, 'receivedDate']"
                  :rules="[{ required: true }]"
                >
                  <DatePicker
                    v-model:value="item.receivedDate"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    class="w-full"
                    :disabled="isFormDisabled"
                  />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem
                  label="到账金额"
                  :name="['receivedDetails', index, 'receivedAmount']"
                  :rules="[{ required: true }]"
                >
                  <InputNumber
                    v-model:value="item.receivedAmount"
                    :precision="2"
                    class="w-full"
                    placeholder="请输入到账金额"
                    :disabled="isFormDisabled"
                    @change="() => calculateItemSettleAmount(item)"
                  />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem
                  label="到账币种"
                  :name="['receivedDetails', index, 'receivedCurrency']"
                  :rules="[{ required: true }]"
                >
                  <Select
                    v-model:value="item.receivedCurrency"
                    :options="getDictOptions('currency')"
                    :getPopupContainer="getPopupContainer"
                    placeholder="请选择到账币种"
                    class="w-full"
                    :disabled="isFormDisabled"
                  />
                </FormItem>
              </Col>
            </Row>
            <Row :gutter="16">
              <Col :span="8">
                <FormItem
                  label="汇率"
                  :name="['receivedDetails', index, 'exchangeRate']"
                  :rules="[{ required: true }]"
                >
                  <InputNumber
                    v-model:value="item.exchangeRate"
                    :precision="4"
                    class="w-full"
                    placeholder="请输入汇率"
                    :disabled="isFormDisabled"
                    @change="() => calculateItemSettleAmount(item)"
                  />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem label="结汇金额">
                  <span>{{
                    item.settleAmount
                      ? Number(item.settleAmount).toLocaleString()
                      : '-'
                  }}</span>
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem
                  label="结汇币种"
                  :name="['receivedDetails', index, 'settleCurrency']"
                  :rules="[{ required: true }]"
                >
                  <Select
                    v-model:value="item.settleCurrency"
                    :options="getDictOptions('currency')"
                    :getPopupContainer="getPopupContainer"
                    placeholder="请选择结汇币种"
                    class="w-full"
                    :disabled="isFormDisabled"
                    @change="
                      () => {
                        item.refundTaxCurrency = item.settleCurrency;
                        calculateItemRefundTaxAmount(item);
                      }
                    "
                  />
                </FormItem>
              </Col>
            </Row>
            <Row :gutter="16">
              <Col :span="8">
                <FormItem label="退税金额">
                  <span>{{
                    item.refundTaxAmount
                      ? Number(item.refundTaxAmount).toLocaleString()
                      : '-'
                  }}</span>
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem label="退税币种">
                  <span>{{
                    getDictOptions('currency').find(
                      (currency) => currency.value === item.refundTaxCurrency,
                    )?.label || '-'
                  }}</span>
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem label="收入小计">
                  <span
                    ><strong>{{
                      item.receiveTotalAmount
                        ? Number(item.receiveTotalAmount).toLocaleString()
                        : '-'
                    }}</strong></span
                  >
                </FormItem>
              </Col>
            </Row>
          </div>
          <!-- 提示信息 -->
          <Row :gutter="16" class="text-notice border-t pb-4 pt-4 text-sm">
            <Col :span="8"> *结汇金额(人民币) = 到账金额 × 汇率 </Col>
            <Col :span="8"> *退税金额(人民币) = 采购金额 ÷ 1.13 × 0.13 </Col>
            <Col :span="8"> *收入小计(人民币) = 退税金额 + 结汇金额 </Col>
          </Row>
          <div class="mb-3">
            <Button
              type="dashed"
              @click="addIncomeItem"
              class="dashed-primary-btn w-full"
              :disabled="isFormDisabled"
            >
              <PlusOutlined /> 添加收入项目
            </Button>
          </div>
          <Row :gutter="16" class="mt-4 border-t pt-4">
            <Col :span="8">
              <FormItem label="收入合计">
                <span class="text-2xl text-green-600">{{
                  formData.receiveTotalAmount
                    ? Number(formData.receiveTotalAmount).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="收入币种">
                <span>人民币(CNY)</span>
              </FormItem>
            </Col>
          </Row>
        </Card>

        <!-- 支出详情 -->
        <Card title="支出详情" class="mb-4">
          <div
            v-for="(item, index) in formData.paidDetails"
            :key="item.id"
            class="expense-item mb-3"
          >
            <div class="mb-3 flex items-center justify-between">
              <span class="font-medium">支出项目 {{ index + 1 }}</span>
              <Button
                type="text"
                danger
                size="small"
                :disabled="isFormDisabled"
                @click="removeExpenseItem(index)"
              >
                <DeleteOutlined /> 删除
              </Button>
            </div>
            <Row :gutter="16">
              <Col :span="8">
                <FormItem label="支出款项">
                  <Select
                    v-model:value="item.paidItem"
                    :options="getDictOptions('paid_item_type')"
                    :getPopupContainer="getPopupContainer"
                    placeholder="请选择支出款项"
                    class="w-full"
                    :disabled="isFormDisabled"
                  />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem label="支出日期">
                  <DatePicker
                    v-model:value="item.paidDate"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    class="w-full"
                    :disabled="isFormDisabled"
                  />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem label="金额">
                  <span>{{
                    item.paidAmount
                      ? Number(item.paidAmount).toLocaleString()
                      : '-'
                  }}</span>
                </FormItem>
              </Col>
            </Row>
          </div>
          <div class="mb-3">
            <Button
              type="dashed"
              @click="addExpenseItem"
              class="dashed-primary-btn w-full"
              :disabled="isFormDisabled"
            >
              <PlusOutlined /> 添加支出项目
            </Button>
          </div>
          <Row :gutter="16" class="mt-4 border-t pt-4">
            <Col :span="8">
              <FormItem label="支出合计">
                <span class="text-2xl text-red-600">{{
                  formData.paidTotalAmount
                    ? Number(formData.paidTotalAmount).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
          </Row>
        </Card>

        <Card title="费用单" class="mb-4">
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="费用单号">
                <span>{{ carCost?.carCostNo || '-' }}</span>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="上牌过户费">
                <span>{{
                  carCost?.plateCost
                    ? Number(carCost.plateCost).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="检测报告费">
                <span>{{
                  carCost?.checkCost
                    ? Number(carCost.checkCost).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="交强险">
                <span>{{
                  carCost?.insuranceCost
                    ? Number(carCost.insuranceCost).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="车船税">
                <span>{{
                  carCost?.vehicleTaxCost
                    ? Number(carCost.vehicleTaxCost).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="清关费">
                <span>{{
                  carCost?.clearCustomsCost
                    ? Number(carCost.clearCustomsCost).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="报关费">
                <span>{{
                  carCost?.declarationCustomsCost
                    ? Number(carCost.declarationCustomsCost).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="运费">
                <span>{{
                  carCost?.shipCost
                    ? Number(carCost.shipCost).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="其他费用">
                <span>{{
                  carCost?.otherCost
                    ? Number(carCost.otherCost).toLocaleString()
                    : '-'
                }}</span>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="费用名称">
                <span>{{ carCost?.otherCostName || '-' }}</span>
              </FormItem>
            </Col>
          </Row>
        </Card>
        <Card title="垫资详情" class="mb-4">
          <div
            v-for="(item, index) in formData.fundedDetails"
            :key="index"
            class="expense-item mb-3"
          >
            <div class="mb-3 flex items-center justify-between">
              <span class="font-medium">垫资项目 {{ index + 1 }}</span>
              <Button
                type="text"
                danger
                size="small"
                :disabled="isFormDisabled"
                @click="removeFundedItem(index)"
              >
                <DeleteOutlined /> 删除
              </Button>
            </div>
            <Row :gutter="16">
              <Col :span="24">
                <FormItem
                  label="利率标准"
                  :name="['fundedDetails', index, 'fundedInterestRate']"
                  :rules="[{ required: true, message: '请输入利率标准' }]"
                >
                  <InputNumber
                    v-model:value="item.fundedInterestRate"
                    :precision="4"
                    :min="0"
                    :max="1"
                    class="w-full"
                    placeholder="请输入利率"
                    :disabled="isFormDisabled"
                    @change="() => calculateFundedInterest(item)"
                  />
                </FormItem>
              </Col>
            </Row>
            <Row :gutter="16">
              <Col :span="8">
                <FormItem
                  label="开始日期"
                  :name="['fundedDetails', index, 'fundedStartDate']"
                  :rules="[{ required: true, message: '请选择开始日期' }]"
                >
                  <DatePicker
                    v-model:value="item.fundedStartDate"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    class="w-full"
                    :disabled="isFormDisabled"
                    @change="() => calculateFundedDays(item)"
                  />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem
                  label="结束日期"
                  :name="['fundedDetails', index, 'fundedEndDate']"
                  :rules="[{ required: true, message: '请选择结束日期' }]"
                >
                  <DatePicker
                    v-model:value="item.fundedEndDate"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    class="w-full"
                    :disabled="isFormDisabled"
                    @change="() => calculateFundedDays(item)"
                  />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem label="垫资天数">
                  <InputNumber
                    v-model:value="item.fundedDays"
                    :min="0"
                    class="w-full"
                    disabled
                    placeholder="自动计算"
                  />
                </FormItem>
              </Col>
            </Row>
            <Row :gutter="16">
              <Col :span="8">
                <FormItem
                  label="垫资金额"
                  :name="['fundedDetails', index, 'fundedAmount']"
                  :rules="[{ required: true, message: '请输入垫资金额' }]"
                >
                  <InputNumber
                    v-model:value="item.fundedAmount"
                    :precision="2"
                    :min="0"
                    class="w-full"
                    placeholder="请输入垫资金额"
                    :disabled="isFormDisabled"
                    @change="() => calculateFundedInterest(item)"
                  />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem label="垫资利息">
                  <InputNumber
                    v-model:value="item.fundedInterest"
                    :precision="2"
                    class="w-full"
                    disabled
                    placeholder="自动计算"
                  />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem
                  label="利息减免"
                  :name="['fundedDetails', index, 'fundedInterestCut']"
                  :rules="[{ required: true, message: '请输入利息减免' }]"
                >
                  <InputNumber
                    v-model:value="item.fundedInterestCut"
                    :precision="2"
                    :min="0"
                    class="w-full"
                    placeholder="请输入减免利息"
                    :disabled="isFormDisabled"
                    @change="calculateTotalAmount"
                  />
                </FormItem>
              </Col>
            </Row>

            <Row :gutter="16">
              <Col :span="8">
                <FormItem
                  label="倒挂利息"
                  :name="['fundedDetails', index, 'fundedInverseInterest']"
                  :rules="[{ required: true, message: '请输入倒挂利息' }]"
                >
                  <InputNumber
                    v-model:value="item.fundedInverseInterest"
                    :precision="2"
                    :min="0"
                    class="w-full"
                    placeholder="请输入倒挂利息"
                    :disabled="isFormDisabled"
                    @change="calculateTotalAmount"
                  />
                </FormItem>
              </Col>
            </Row>

            <Row :gutter="16">
              <Col :span="24">
                <FormItem label="垫资备注">
                  <Textarea
                    v-model:value="item.remark"
                    placeholder="请输入备注"
                    :disabled="isFormDisabled"
                  />
                </FormItem>
              </Col>
            </Row>
          </div>
          <div class="mb-3">
            <Button
              type="dashed"
              @click="addFundedItem"
              class="dashed-primary-btn w-full"
              :disabled="isFormDisabled"
            >
              <PlusOutlined /> 添加垫资项目
            </Button>
          </div>
        </Card>
        <Row :gutter="16" class="mt-4 border-t pt-4">
          <Col :span="8">
            <FormItem label="费用合计">
              <span class="text-2xl text-blue-600">{{
                formData.totalAmount
                  ? Number(formData.totalAmount).toLocaleString()
                  : '-'
              }}</span>
            </FormItem>
          </Col>
        </Row>
        <!-- 驳回原因 -->
        <Card v-if="showRejectReason" title="驳回原因" class="mb-4">
          <Row>
            <Col :span="24">
              <FormItem>
                <Textarea
                  v-model:value="formData.rejectReason"
                  :rows="3"
                  readonly
                  placeholder="暂无驳回原因"
                />
              </FormItem>
            </Col>
          </Row>
        </Card>

        <!-- 备注 -->
        <Card>
          <Row>
            <Col :span="12">
              <FormItem
                label="附件"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 18 }"
              >
                <!-- props参考apps/web-antd/src/components/upload/src/props.d.ts -->
                <!-- maxCount为1(默认)时只允许上传一个文件 会自动绑定为string而非string[] -->
                <FileUpload
                  :max-count="1"
                  v-model:value="formData.costPic"
                  :disabled="isFormDisabled"
                  accept=".jpg,.jpeg,.png,.gif,.webp,.xlsx,.csv,.docx,.pdf"
                />
              </FormItem>
            </Col>
          </Row>
        </Card>
      </div>
    </Form>
  </BasicDrawer>
</template>

<style scoped>
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.form-item label {
  font-weight: 500;
  margin-right: 8px;
  min-width: 80px;
}

.expense-item {
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  padding: 16px;
  background-color: #fafafa;
}

.expense-item:last-child {
  margin-bottom: 0;
}

:deep(.ant-card-head-title) {
  font-weight: 600;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
}
.text-notice {
  color: red;
}

.dashed-primary-btn {
  border-color: #1890ff !important;
  color: #1890ff !important;
}

.dashed-primary-btn:hover {
  border-color: #40a9ff !important;
  color: #40a9ff !important;
}

.dashed-primary-btn:focus {
  border-color: #40a9ff !important;
  color: #40a9ff !important;
}
</style>
